<template>
  <div class="wrap">
    <div class="health-top" @click="handleUpload">
      <div class="h-upload">
        <img :src="healthUrl" />
        <text class="txt">{{ tips }}</text>
      </div>
    </div>
    <div class="status-wrap">
      <div class="title">健康证信息</div>
      <div class="item">
        <div class="left">健康证状态：</div>
        <div class="right">
          {{ healthInfo.verified == 1 ? '已核验' : '未核验' }}
        </div>
      </div>
      <div class="item">
        <div class="left">核验结果：</div>
        <div class="right">
          <div class="one">
            {{ healthInfo.approved == 1 ? '已通过' : '未通过' }}
          </div>
        </div>
        <div class="two" v-show="healthInfo.approved == 0">
          {{ healthInfo.reason }}
        </div>
      </div>
      <div class="item">
        <div class="left">剩余有效天数：</div>
        <div class="right">
          {{ healthInfo.valid_days ? healthInfo.valid_days : '0' }} 天
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// import wx from 'weixin-js-sdk';
import { onMounted, ref, watch } from 'vue'
import { showToast } from 'vant'
import { postData } from '@/request/request.js'
import { useRoute, useRouter } from 'vue-router'
let router = useRouter()
let route = useRoute()
let query = route.query
localStorage.clear()
localStorage.setItem('user_id', query.user_id)
localStorage.setItem('access_token', query.access_token)
localStorage.setItem('open_id', query.open_id)
localStorage.setItem('currentPath', query.currentPath)

const healthUrl = ref('https://ya30images.hbwlife.com/wxmp/health-default.png')
const healthInfo = ref('')
const tips = ref('点击上传健康证')

const user_id = route.query.user_id

let wxConfig = () => {
  var url = window.location.href.split('#')[0]
  postData('/wxaccess/oa/jsapi/signature', {
    url: url,
  }).then((res) => {
    wx &&
      wx.config({
        beta: true,
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: 'wxaa5d43496694b970', // 必填，此时是公众号的id.一致
        timestamp: res.datas.timestamp, // 必填，生成签名的时间戳
        nonceStr: res.datas.noncestr, // 必填，生成签名的随机串
        signature: res.datas.signature, // 必填，签名
        jsApiList: ['chooseImage', 'previewImage'], // 必填，需要使用的JS接口列表
        openTagList: ['wx-open-launch-weapp'], // 跳转小程序时
      })
    wx.ready(function () {
      console.log('config is success')
    })
    wx.error(function (err) {
      console.log(JSON.stringify(err))
    })
  })
}

//初始获取健康证
const getHealthInfo = () => {
  postData('/user/health/info/get')
    .then((res) => {
      healthUrl.value = res?.datas?.image_url || ''
      healthInfo.value = res?.datas || {}
      if (res?.datas?.image_url === '') {
        tips.value = '上传健康证'
        healthUrl.value =
          'https://ya30images.hbwlife.com/wxmp/health-default.png'
      } else {
        tips.value = '更新健康证'
        healthUrl.value =
          res?.datas?.image_url + '?v=' + new Date().getTime() || ''
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const fn_upload = (str) => {
  let param = { user_id: user_id, image_base64: str, image_ext: 'jpeg' }
  postData('/user/health/base64image/upload', param)
    .then((res) => {
      if (+res?.code === 0) {
        healthUrl.value = res?.datas?.url + '?v=' + new Date().getTime() || ''
        showToast('上传成功')
        // setTimeout(() => {
        //   wx &&
        //     wx.miniProgram.navigateTo({
        //       url: '/pagesC/myInfo/index',
        //     })
        // }, 2000)
        setTimeout(() => {
          wx &&
            wx.miniProgram.navigateTo({
              url: '/pagesC/subMessage/index',
            })
        }, 2000)
      } else if (res.code == '-57022') {
        showToast('请先上传人脸识别照片')
        setTimeout(() => {
          wx &&
            wx.miniProgram.navigateTo({
              url: `/pagesC/myInfo/userFacephoto`,
            })
        }, 2000)
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

// 健康证上传
const handleUpload = () => {
  wx &&
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: (imgRes) => {
        let localIds = imgRes.localIds
        if (Array.isArray(localIds) && localIds.length) {
          wx &&
            wx.getLocalImgData({
              localId: localIds[0],
              success: (localImgRes) => {
                let localData = localImgRes.localData
                let imageBase64 = ''

                if (localData.indexOf('data:image') === 0) {
                  // 苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                  imageBase64 = localData
                } else {
                  // 此处是安卓中的唯一得的坑！在拼接前需要对localData进行换行符的全局替换
                  // 此时一个正常的 base64 图片路径就完美生成赋值到 img 的 src 中了
                  imageBase64 = `data:image/jpeg;base64,${localData.replace(
                    /\n/g,
                    ''
                  )}`
                }
                imageBase64 && fn_upload(imageBase64) //上传健康证
              },
              fail: (localImgErr) => {
                console.log(localImgErr?.errMsg)
              },
            })
        }
      },
      fail: (imgErr) => {
        console.log(imgErr?.errMsg)
      },
    })
}

onMounted(() => {
  wxConfig()
  getHealthInfo()
})

watch(
  () => route.fullPath,
  () => {
    wxConfig()
    getHealthInfo()
  }
)
</script>

<style scoped>
.wrap {
  margin: 0;
  padding: 0;
  font-size: 0.16rem;
  color: #333;
}
.health-top {
  width: 100%;
  height: auto;
  padding: 0.1rem;
  margin-top: 0.15rem;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.health-top .u-upload {
  padding: 0.1rem;
  box-sizing: border-box;
}
.health-top img {
  width: 1.5rem;
  height: auto;
  object-fit: contain;
}
.health-top .txt {
  font-size: 0.14rem;
  color: #d5ad57;
  margin: 0 auto;
  margin-top: 0.2rem;
}
::v-deep .h-upload {
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
}
.status-wrap {
  margin-top: 0.3rem;
  padding: 0 0.1rem;
  box-sizing: border-box;
  background: #fff;
  display: flex;
  flex-flow: column;
  justify-content: flex-start;
}
.status-wrap .title {
  font-size: 0.16rem;
  font-weight: bold;
  padding: 0 0.1rem;
  position: relative;
  padding-left: 13px;
  margin: 24px 0;
}
.status-wrap .title:before {
  content: '';
  background-color: #d5ad57;
  width: 0.035rem;
  height: 0.2rem;
  position: absolute;
  left: 0;
  top: 47%;
  margin-top: -8px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
}
.status-wrap .item {
  background: #fff;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 0.5rem;
  border-bottom: 1px solid #f5f5f0;
  padding: 0 0.1rem;
  font-size: 0.16rem;
  margin-bottom: 0.1rem;
}
.status-wrap .item .right {
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: flex-start;
}
.item .two {
  margin-top: 0.05rem;
  color: #c73a3a;
  font-size: 0.14rem;
  margin-left: 0.1rem;
}
</style>
